package com.hkfrich.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkfrich.common.constant.Constants;
import com.hkfrich.common.utils.SecurityUtils;
import com.hkfrich.common.utils.StringUtils;
import com.hkfrich.system.domain.SysRole;
import com.hkfrich.system.domain.SysUserRole;
import com.hkfrich.system.service.SysRoleService;
import com.hkfrich.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.hkfrich.common.controller.BaseController;
import com.hkfrich.common.utils.ConvertUtils;
import com.hkfrich.common.utils.ResultUtils;
import com.hkfrich.system.domain.SysUser;
import com.hkfrich.system.service.SysUserService;
/**
 * @ClassName TestController
 * @Desscription
 * @Author _HeiShuai
 * @Date 2022/8/31 19:39
 * @Version 1.0
 **/

@Controller
@RequestMapping(value = "/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 通过条件查询单个用户 不分页
     */
    @RequestMapping("/getOne")
    @ResponseBody
    public ResultUtils getOne(@RequestBody SysUser sysUser) {
        QueryWrapper<SysUser> query = initBaseQueryWrapper(sysUser);
        SysUser one = sysUserService.getOne(query);
        return ResultUtils.success(one,"用户查询成功");
    }

    /**
     * 获取用户详细信息 包括角色权限
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public ResultUtils getUser(@RequestBody SysUser sysUser) {
         return ResultUtils.success(sysUserService.selectUserAndRoles(sysUser),"用户查询成功");
    }


    /**
     * 通过id查询单个用户
     */
    @RequestMapping("/getOneById")
    @ResponseBody
    public ResultUtils getOneById(@RequestBody String paramsStr) {
        JSONObject params = getBodyParamsByStr(paramsStr);
        Integer id = params.getInteger("id");
        SysUser one = sysUserService.getById(id);
        return ResultUtils.success(one,"用户查询成功");
    }

    /**
     * 查询用户列表  分页
     */
    @PreAuthorize("hasAnyAuthority('system:user:query')")
    @RequestMapping("/list")
    @ResponseBody
    public ResultUtils list(@RequestBody SysUser sysUser) {
        Page<SysUser> page = initBaseQueryPageWrapper(sysUser);
        QueryWrapper<SysUser> query = initBaseQueryWrapper(sysUser);
        query.ne(Constants.DEL_FLAG_COLUMN,Constants.DEL_FLAG_VALUE);
        Page<SysUser> pageGrid = sysUserService.page(page, query);
        return ResultUtils.success(pageGrid,"用户列表查询成功");
    }

    /**
     * 新增用户
     */
    @PreAuthorize("hasAnyAuthority('system:user:save')")
    @RequestMapping("/save")
    @ResponseBody
    @Transactional
    public ResultUtils save(@RequestBody SysUser sysUser)
    {
        if (StringUtils.isNotEmpty(sysUser.getUserName()) && Constants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(sysUser))) {
            return ResultUtils.fail("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && Constants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser))) {
            return ResultUtils.fail("新增用户'" + sysUser.getPhonenumber() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getEmail()) && Constants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser))) {
            return ResultUtils.fail("新增用户'" + sysUser.getEmail() + "'失败，邮箱账号已存在");
        }
        sysUser.setCreateBy(SecurityUtils.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUserService.save(sysUser);
        sysUser.getRoleIds().stream().forEach( rId -> sysUserRoleService.save(new SysUserRole(sysUser.getUserId(),rId)));
        return ResultUtils.success("用户保存成功");
    }

    /**
     * 修改用户
     */
    @PreAuthorize("hasAnyAuthority('system:user:update')")
    @RequestMapping("/updateById")
    @ResponseBody
    @Transactional
    public ResultUtils updateById(@RequestBody SysUser sysUser)
    {
        if (StringUtils.isNotEmpty(sysUser.getUserName()) && Constants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(sysUser))) {
            return ResultUtils.fail("修改用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && Constants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser))) {
            return ResultUtils.fail("修改用户'" + sysUser.getPhonenumber() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getEmail()) && Constants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser))) {
            return ResultUtils.fail("修改用户'" + sysUser.getEmail() + "'失败，邮箱账号已存在");
        }
        LambdaQueryWrapper<SysUserRole> query = new LambdaQueryWrapper<>();
        query.eq(SysUserRole::getUserId,sysUser.getUserId());
        sysUserRoleService.remove(query);
        sysUser.getRoleIds().stream().forEach( rId -> sysUserRoleService.save(new SysUserRole(sysUser.getUserId(),rId)));
        sysUser.setUpdateBy(SecurityUtils.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUserService.updateById(sysUser);
        return ResultUtils.success("用户修改成功");
    }

    /**
     * 删除用户
     */
    @PreAuthorize("hasAnyAuthority('system:user:remove')")
    @RequestMapping("/removeById")
    @ResponseBody
    public ResultUtils removeById(@RequestBody String paramsStr)
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        Integer id = params.getInteger("id");
        return ResultUtils.success(sysUserService.removeById(id),"用户删除成功");
    }

    /**
     * 批量删除用户
     */
    @PreAuthorize("hasAnyAuthority('system:user:remove')")
    @RequestMapping("/removeByIds")
    @ResponseBody
    @Transactional
    public ResultUtils removeByIds(@RequestBody String paramsStr)
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        String ids = params.getString("ids");
        if (ids.contains(SecurityUtils.getUserId().toString())){
            return ResultUtils.fail("当前登录用户不能删除");
        }
        List<Long> list = ConvertUtils.toList(ids);
        list.stream().forEach( id -> sysUserService.update(new LambdaUpdateWrapper<SysUser>().set(SysUser::getDelFlag,Constants.DEL_FLAG_VALUE).eq(SysUser::getUserId,id)));
        list.stream().forEach( id -> sysUserRoleService.remove(new LambdaUpdateWrapper<SysUserRole>().eq(SysUserRole::getUserId,id)));
        return ResultUtils.success("删除用户成功");
    }

    /**
     * 修改启用状态
     */
    @RequestMapping("/changeUserStatus")
    @ResponseBody
    public ResultUtils changeUserStatus(@RequestBody SysUser sysUser) {
        return ResultUtils.success(sysUserService.updateById(sysUser),Constants.STATUS_DISABLE.equals(sysUser.getStatus())?"停用成功":"启用成功");
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetUserPwd")
    @ResponseBody
    public ResultUtils resetUserPwd(@RequestBody SysUser sysUser) {
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        return ResultUtils.success(sysUserService.updateById(sysUser),"重置成功");
    }


}
